package com.ruoyi.web.controller.ai;

import com.ruoyi.common.core.controller.BaseController;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Objects;

/**
 * 会话Controller
 *
 * @author gdk
 * @date 2023-05-15
 */
@Controller
@RequiredArgsConstructor
@RequestMapping("/ai/chat/test")
public class AIChatTestController extends BaseController {
    private SseEmitter sse;

    /**
     * 建立连接
     *
     * @return {@link SseEmitter}
     * @author gdk
     * @since 2023/5/15 20:28
     */
    @SneakyThrows
    @GetMapping("/sse")
    public SseEmitter sse() {
        // 设置永不过期
        sse = new SseEmitter(0L);
        sse.send(SseEmitter.event().name("connect").data("连接建立成功"));
        return sse;
    }

    /**
     * 向上面建立了连接的客户端发送消息
     *
     * @param prompt 消息
     * @return {@link String}
     * @author gdk
     * @since 2023/5/15 20:29
     */
    @SneakyThrows
    @GetMapping("/sse/send")
    @ResponseBody
    public String sseSend(String prompt) {
        if (Objects.isNull(sse)) {
            return "没有sse连接";
        }

        sse.send(prompt);
        return "消息发送成功";
    }
}
